package setup

import (
	"context"
	ginzap "github.com/gin-contrib/zap"
	"github.com/gin-gonic/gin"
	httptransport "github.com/go-kit/kit/transport/http"
	"github.com/shinedone/srv-framework/pkg/asserts"
	"github.com/shinedone/srv-framework/pkg/beans"
	"github.com/shinedone/srv-framework/pkg/gins"
	"github.com/shinedone/srv-server/internal/global/instance"
	enterpriseRest "github.com/shinedone/srv-server/internal/modules/enterprise/restful"
	"go.uber.org/zap"
	"net"
	"net/http"
	"time"
)

// 初始化Gqlgen
func RestfulInit(errCh chan error) {
	config := instance.GetConfig()
	appLog := instance.GetAppLog()
	kitLog := instance.GetKitLog()
	httpAddress := config.Restful.Address
	httpListener, err := net.Listen("tcp", httpAddress)
	asserts.Nil(err, err)
	// gin设置
	gin.SetMode(gin.ReleaseMode)
	ginLogger := appLog.WithOptions(zap.WithCaller(false))
	router := gin.Default()
	// 设置通用中间件
	router.Use(ginzap.Ginzap(ginLogger, time.RFC3339, true))
	router.Use(ginzap.RecoveryWithZap(ginLogger, true))
	// 注册路由
	routerRegister(router)
	// http启动
	go func() {
		_ = kitLog.Log("transport", "HTTP", "addr", httpAddress)
		errCh <- router.RunListener(httpListener)
	}()
}

// 路由注册
func routerRegister(router *gin.Engine) {
	// 初始化endpoint
	enterpriseHandlers := &enterpriseRest.Handlers{}
	err := beans.ProvideBean(enterpriseHandlers)
	asserts.Nil(err, err)

	err = beans.Populate()
	asserts.Nil(err, err)

	// 注册路由
	router.Any("adm/enterprise/rest/getById", func(ginCtx *gin.Context) {
		server := httptransport.NewServer(
			enterpriseHandlers.GetById(),
			func(ctx context.Context, req *http.Request) (request interface{}, err error) {
				return ginCtx.Query("id"), nil
			},
			gins.NewJsonResponseDecoder(ginCtx))
		server.ServeHTTP(ginCtx.Writer, ginCtx.Request)
	})
	router.Any("adm/enterprise/rest/list", func(ginCtx *gin.Context) {
		server := httptransport.NewServer(
			enterpriseHandlers.QueryEnterprise(),
			func(ctx context.Context, req *http.Request) (request interface{}, err error) {
				var resp = &enterpriseRest.QueryEnterpriseReq{}
				err = ginCtx.BindJSON(resp)
				if err != nil {
					return nil, err
				}
				return resp, nil
			},
			gins.NewJsonResponseDecoder(ginCtx))
		server.ServeHTTP(ginCtx.Writer, ginCtx.Request)
	})

}
